package com.fengniaoxls.fengniaonewretail.utils;

import com.fengniaoxls.fengniaonewretail.net.factory.NullStringToEmptyAdapterFactory;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;


import java.lang.reflect.Type;
import java.util.ArrayList;

public class GsonUtil {
    private static GsonUtil gsonUtil;

    public static GsonUtil getInstance() {
        if (gsonUtil == null) {
            synchronized (GsonUtil.class) {
                if (gsonUtil == null) {
                    gsonUtil = new GsonUtil();
                }
            }
        }
        return gsonUtil;
    }

    /**
     * 用来解析对象
     */
    public <T> T fromJsonObject(Object json, Class<T> type) {
        return new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).serializeNulls().create().fromJson(new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).serializeNulls().create().toJson(json), type);
    }

    /**
     * 用来解析集合
     */
    public <T> ArrayList<T> fromJsonArray(Object json, Class<T> clazz) {
        Type type = new TypeToken<ArrayList<JsonObject>>() {
        }.getType();
        ArrayList<JsonObject> jsonObjects = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).serializeNulls().create().fromJson(new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).serializeNulls().create().toJson(json), type);
        ArrayList<T> arrayList = new ArrayList<>();
        for (JsonObject jsonObject : jsonObjects) {
            arrayList.add(new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).serializeNulls().create().fromJson(jsonObject, clazz));
        }
        return arrayList;
    }

    public JsonElement getJsonElement(String jsonString, String jsonElementKey) {
        JsonElement jsonElement = new JsonParser().parse(jsonString).getAsJsonObject().get(jsonElementKey);
        return jsonElement;
    }
}
